﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.Status;
using Microsoft.WindowsMobile.PocketOutlook;

namespace SMSNotifierCore
{
    public class CoreLogic
    {
        public CoreLogic()
        {
            _config = SMSsettings.ReadFromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\SMSNotifierSettings.xml");
        }

        private SMSsettings _config;
        public SMSsettings Config
        {
            get { return _config; }
        }

        private int _numberOfMissedCalls;
        public int NumberOfMissedCalls
        {
            get { return _numberOfMissedCalls; }
            set { _numberOfMissedCalls = value; }
        }

        public void missedCalls_Changed(object sender, ChangeEventArgs args)
        {
            try
            {
                // Only react when the number of missed calls counter goes up.
                // It seems to go down when the user calls back the previously unanswered caller!
                if (_numberOfMissedCalls < SystemState.PhoneMissedCalls)
                {
                    Contact caller = SystemState.PhoneLastIncomingCallerContact;
                    if (null != caller) // We know who the caller is as a Contact
                    {
                        string message = "";
                        Boolean bSend = true;
                        if (_config.SendSMSToUnansweredCallers)
                        {
                            bSend = _ShouldSMSBeSent();
                            if (bSend)
                            {
                                message = _config.SMSMessageToSend; 
                                if (_config.AppendNextFreeSlotMessage) 
                                {
                                    message += " ";
                                    message += _GetNextFreeSlotText(_config.FreeSlotTextFormat); 
                                }
                                _SendReplySMSToCaller(SystemState.PhoneLastIncomingCallerNumber, message);
                            }
                        }
                        else
                        {
                            bSend = false;
                        }
                        if (_config.AddMissedCallInfoToCalendar) 
                            _CreateCalendarAppointment(caller, message, SystemState.PhoneLastIncomingCallerNumber, bSend);
                    }
                    else
                    {   // Caller is not a contact, but we know the number
                        string message = "";
                        Boolean bSend = true;
                        if (_config.SendSMSToUnansweredCallers) 
                        {
                            bSend = _ShouldSMSBeSent();
                            if (bSend)
                            {
                                message = _config.SMSMessageToSend; 
                                if (_config.AppendNextFreeSlotMessage) 
                                {
                                    message += " ";
                                    message += _GetNextFreeSlotText(_config.FreeSlotTextFormat); 
                                }
                                _SendReplySMSToCaller(SystemState.PhoneLastIncomingCallerNumber, message);
                            }
                        }
                        else
                        {
                            bSend = false;
                        }
                        if (_config.AddMissedCallInfoToCalendar) 
                            _CreateCalendarAppointment(null, message, SystemState.PhoneLastIncomingCallerNumber, bSend);
                    }
                }
            }
            catch { }
            finally
            {
                _numberOfMissedCalls = SystemState.PhoneMissedCalls;
            }
        }

        private Boolean _ShouldSMSBeSent()
        {
            Boolean bSend = false;
            if (_config.SendSMSOnlyWhenActiveAppointment) 
            {
                bSend = false;
                Appointment a = SystemState.CalendarAppointment;
                if (a != null)
                {
                    if (_config.SendSMSOnlyWhenBusyAppointment) 
                    {
                        if (a.BusyStatus == BusyStatus.Busy ||
                            a.BusyStatus == BusyStatus.OutOfOffice)
                        {
                            bSend = true;
                        }
                    }
                    else
                    {
                        bSend = true;
                    }
                }
            }
            else
            {
                bSend = true;
            }
            return bSend;
        }

        private string _GetNextFreeSlotText(string formatString)
        {
            // TODO: what if we have multiple appointments either 
            // simultaneously or adjacent to each other?
            Appointment a = SystemState.CalendarAppointment;
            string s = "";
            if (a != null)
            {
                DateTime dtEnd = a.End;
                s = string.Format(formatString, dtEnd.ToShortTimeString());
            }
            return s;
        }

        private void _CreateCalendarAppointment(Contact caller, string SMSMessage, string SMSNumber, Boolean SMSWasSent)
        {
            OutlookSession s = new OutlookSession();
            Appointment app = new Appointment();
            app.BusyStatus = BusyStatus.Free;
            app.ReminderSet = false;
            //app.Start = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
            app.Start = DateTime.Now;
            app.Duration = TimeSpan.FromMinutes(1);
            string body = "";
            if (caller != null) // we know the caller as a Contact
            {
                app.Subject = "Call from " + caller.FirstName + " " + caller.LastName;
                body = "Call from " + caller.FirstName + " " + caller.LastName + _GetTitleAndCompany(caller) + " was missed. ";
            }
            else // we know just the phone number
            {
                app.Subject = "Call from " + SMSNumber + " (not in Contacts)";
                body = "Call from " + SMSNumber + " (not in Contacts) was missed. ";
            }
            if (SMSWasSent)
                body += "An SMS message was sent to " + SMSNumber + ": " + SMSMessage;
            app.Body = body;
            s.Appointments.Items.Add(app);
        }

        private string _GetTitleAndCompany(Contact caller)
        {
            string s = "";

            string[] p = new string[] { caller.JobTitle, caller.CompanyName };
            foreach (string ps in p)
            {
                if (ps != string.Empty)
                    if (s.Length == 0)
                        s = ps;
                    else
                        s += ", " + ps;
            }
            if (s.Length > 0)
                s = " (" + s + ")";
            return s;
        }

        private void _SendReplySMSToCaller(string CallerNumber, string text)
        {
            OutlookSession s = new OutlookSession();
            SmsAccount acct = s.SmsAccount;
            // Strip away space, parenthesis and minus, they seem to affect the sending of SMS
            SmsMessage sms = new SmsMessage(CallerNumber.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", ""), text);
            acct.Send(sms);
        }

        public void OpenProjectHomepage()
        {
            string sUrl = @"https://www.codeplex.com/SMSNotifier";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "iexplore.exe";
            p.StartInfo.Arguments = sUrl;
            p.Start();
        }

        public void OpenProjectReleases()
        {
            string sUrl = @"https://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=SMSNotifier";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "iexplore.exe";
            p.StartInfo.Arguments = sUrl;
            p.Start();
        }
    }
}
